package com.software.lease.common.utils;

import com.software.lease.common.exception.LeaseException;
import com.software.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static long tokenExpiration =  60 * 60 * 60 * 1000L;
    private  static SecretKey secretKey = Keys.hmacShaKeyFor("abcdabcdabcdabcdabcdabcdabcdabcd".getBytes());

    /**
     * 生成token
     * @param userId
     * @param username
     * @return
     */
    public static String createToken(Long userId, String username){
        String jwt = Jwts.builder()
                .claim("userId", userId)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))//设置过期时间
                .setSubject("LOGIN_USER")
                .claim("username", username)
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();
        return jwt;
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims parseToken(String token){
        if(token == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }

        try{
            JwtParser parser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            return parser.parseClaimsJws(token).getBody();

        }catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    //测试
    public static void main(String[] args) {
        System.out.println(createToken(1L, "username"));
        System.out.println(parseToken(createToken(1L, "username")));

    }
}
